# @Time:   2020/12/8 11:24
# @Author: Zong Wei

from selenium import webdriver

# Set browser driver and parameter
from ui_automation_testing.utils.config import DRIVER_PATH, DATA_PATH

CHROME_DRIVER_PATH = DRIVER_PATH + '\\chromedriver.exe'
IE_DRIVER_PATH = DRIVER_PATH + '\\IEDriverServer.exe'
FIREFOX_DRIVER_PATH = DRIVER_PATH + '\\geckodriver.exe'

TYPES = {'firefox': webdriver.Firefox, 'chrome': webdriver.Chrome, 'ie': webdriver.ie}
EXECUTABLE_PATH = {'firefox': FIREFOX_DRIVER_PATH, 'chrome': CHROME_DRIVER_PATH, 'ie': IE_DRIVER_PATH}


class Browser:
    browser_type = None
    option = None
    driver = None

    def set_browser(self, browser_type='chrome'):
        self.browser_type = browser_type
        if browser_type == 'chrome':
            self.option = webdriver.ChromeOptions()
            # self.option.add_argument('disable-infobars')    # 只适用于旧版本浏览器
            self.option.add_experimental_option("excludeSwitches", ['enable-automation'])  # 用于新版本浏览器
            self.option.add_argument('--start-maximized')
            # self.option.add_argument('lang=en_US')
            # self.option.add_argument('headless')
            # self.option.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片, 提升速度
            self.option.add_argument('--no-sandbox')  # 解决DevToolsActivePort文件不存在的报错
            self.option.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug

            # ua = 'Chrome/87.0.4280.66'
            # self.option.add_argument('user-agent=' + ua)

            # prefs1 = {"download.default_directory": "/data"}
            # self.option.add_experimental_option("prefs", prefs1)  # 指定下载位置，无作用

            self.option.add_argument('window-size=1920x1080')  # 指定浏览器分辨率,可在headless模式下运行
            # self.option.add_argument('--hide-scrollbars')  # 隐藏滚动条, 应对一些特殊页面

            # 禁止加载部分图片
            # prefs = {'profile.default_content_setting_values': {'images': 2}}
            # self.option.add_experimental_option('prefs', prefs)

            prefs = dict()
            prefs["credentials_enable_service"] = False
            prefs["profile.password_manager_enabled"] = False
            self.option.add_experimental_option("prefs", prefs)  # 屏蔽'保存密码'提示框

            self.driver = TYPES[self.browser_type](options=self.option,
                                                   executable_path=EXECUTABLE_PATH[self.browser_type])

            # 以下配置即可在headless模式下载
            self.driver.command_executor._commands["send_command"] = (
                "POST", '/session/$sessionId/chromium/send_command')
            params = {'cmd': 'Page.setDownloadBehavior',
                      'params': {'behavior': 'allow',
                                 'downloadPath': DATA_PATH+'\\download'}}
            self.driver.execute("send_command", params=params)
            return self.driver
